<template>
  <div class="user">
    <div class="top">
      设置
    </div>
    <el-divider />
    <div class="content">
      <el-tabs tab-position="left" style="height: 600px;" class="demo-tabs">
        <el-tab-pane label="个人设置">
          <div>
            <div style="margin-bottom: 30px;font-weight: bold;">个人设置</div>
            <el-form :model="userFormData" label-width="100px">
              <el-form-item label="头像">
                <div class="img_area">
                  <img :src="url" @click="chooseType"/>
                  <input 
                    type="file"
                    id="upload"
                    ref="inputer"
                    @change="uploadImg($event)"
                    multiple
                    accept="image/*"
                    style="display:none"/>
                </div>
              </el-form-item>
              <el-form-item label="昵称">
                <el-input v-model="userFormData.nickname" placeholder="请输入昵称" />
              </el-form-item>
              <el-form-item label="身份证">
                <el-input v-model="userFormData.id_card" show-password placeholder="请输入身份证号" />
              </el-form-item>
              <el-form-item label="年龄">
                <el-input v-model="userFormData.age" placeholder="请输入年龄" />
              </el-form-item>
              <el-form-item label="性别">
                <el-radio-group v-model="userFormData.sex">
                  <el-radio :label="0">男</el-radio>
                  <el-radio :label="1">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="爱好">
                <el-input
                  v-model="userFormData.hobby"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  placeholder="请输入您的爱好！"
                />
              </el-form-item>
              <el-form-item label="心情">
                <el-input
                  v-model="userFormData.mood"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  placeholder="请输入您的心情状态！"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmit" style="margin-top: 50px;width: 80px;">提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        <el-tab-pane label="密码设置">
          <div>
            <div style="margin-bottom: 60px;font-weight: bold;">密码设置</div>
            <el-form
              :model="passwordForm"
              :rules="passwordRules"
              ref="passwordFormRef"
              label-width="100px"
            >
              <el-form-item label="旧密码" prop="old_password">
                <el-input v-model="passwordForm.old_password" show-password placeholder="请输入旧密码" />
              </el-form-item>
              <el-form-item label="新密码" prop="new_password" style="margin: 30px 0px;">
                <el-input v-model="passwordForm.new_password" show-password placeholder="请输入新密码" />
              </el-form-item>
              <el-form-item label="确认新密码" prop="confirm_password">
                <el-input v-model="passwordForm.confirm_password" show-password placeholder="请再次输入新密码" />
              </el-form-item>
              <el-form-item>
                <div style="margin-top: 80px;">
                  <el-button type="success" @click="submitPasswordForm(passwordFormRef)">提交</el-button>
                  <el-button @click="resetForm(passwordFormRef)">重置</el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {getCookies, setCookies} from '../../utils/auth.js'
import {userController} from '../../api'
import type { FormInstance, FormRules } from 'element-plus'
import {fileStore} from '../../store'
import {encryptDes,RSAencrypt} from '../../utils/des.js'
import { useRouter } from 'vue-router'


const router = useRouter()
// 获取pinia中的实例
const fileMainStore = fileStore()

//头像保存地址
const url = ref("")
//保存上传文件
let file = ref(null)

// 用户信息表单
const userFormData = reactive({
  age: null,
  avatar: null,
  hobby: null,
  id_card: null,
  mood: null,
  nickname: null,
  sex: 0,
  user_id: null
})

// 修改密码表单对象
const passwordFormRef = ref<FormInstance>()
// 用户密码信息表单
const passwordForm = reactive({
  new_password: '',
  confirm_password: '', // 确认密码
  old_password: '',
  user_id: '',
  rsa_kv:'',
  des_kv:undefined
})

const passwordRules = reactive<FormRules>({
  old_password: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
  ],
  new_password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
  ],
  confirm_password: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
  ],
})

const username=getCookies('username')
const user_id = getCookies('user_id')

onMounted(() => {
  getUserData()
  getRSAKey()
})

// 获取用户数据
const getUserData = async () => {
  const user_id = getCookies('user_id')
  const username = getCookies('username')
  const res = await userController.getUserDetail({user_id: user_id, user_name: username})
  const userData = res.data.data
  console.log('用户数据==00')
  console.log(res)
  if(res.data.code === 200) {
    userFormData.age = userData.age
    userFormData.avatar = userData.avatar
    userFormData.hobby = userData.hobby
    userFormData.id_card = userData.id_card
    userFormData.mood = userData.mood
    userFormData.nickname = userData.nickname
    userFormData.sex = userData.sex
    userFormData.user_id = userData.app_user_id
    url.value = res.data.data.avatar
    passwordForm.user_id = userData.app_user_id
    console.log(userFormData)
  }
}

// 点击头像时触发input输入框
function chooseType() {
    document.getElementById("upload").click();
}
async function gotoLogin() {
    passwordForm.old_password = encryptDes(passwordForm.old_password,"QU*%123+CHEN+qwer123+456+&*+"+username);
    passwordForm.new_password = encryptDes(passwordForm.new_password,"QU*%123+CHEN+qwer123+456+&*+"+username);
    
    passwordForm.des_kv =RSAencrypt("QU*%123+CHEN+qwer123+456+&*+"+username,passwordForm.rsa_kv);
    
     //登陆     
     const res= await userController.updatePwd({user_id:user_id,old_password:passwordForm.old_password,
                new_password:passwordForm.new_password,rsa_kv:passwordForm.rsa_kv,des_kv:passwordForm.des_kv})
     console.log(res);
     
     if(res.data.code === 200)
    {
      let data = res.data.data;
      ElMessage({message: '修改成功', type: 'success'})
      router.push({ name: '/login' })

    }else{
      ElMessage({message: '修改失败', type: 'danger'})
    }
}

//获取密钥
async function getRSAKey() {
  const res = await userController.getRSAKey()
  if(res.data.code === 200) {
    console.log(res);
    passwordForm.rsa_kv = res.data.data.publicKey
    
  }
}
// 图片上传方法
async function uploadImg(event) {
    file = event.target.files[0]
    let formDate = new FormData();
    formDate.append("file",file)
    const res = await userController.getHeadUrl(formDate)
    if(res.data.code == 200) {
        url.value = res.data.data.avatar
        userFormData.avatar = res.data.data.avatar
    }
}

// 修改用户信息
const onSubmit = async () => {
  // console.log(userFormData)
  const res = await userController.updateUser(userFormData)
  console.log(res)
  if(res.data.code === 200) {
    ElMessage({message: '修改成功', type: 'success'})
    // setCookies('user', JSON.stringify(userFormData))
    fileMainStore.save_Url(userFormData.avatar)
    // window.location.reload() 
    getUserData()
  }
}
// 修改用户密码
const submitPasswordForm = async (formEl: FormInstance | undefined) => {
  if(!formEl) return
  await formEl.validate((valid, fields) => {
    if(valid) {
      console.log('验证通过')
      console.log(passwordForm)
      gotoLogin()
      // const res = await userController.updatePwd(passwordForm)
    } else {
      console.log('验证不通过')
    }
  })
}
// 密码表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


</script>

<style lang="scss" scoped>
.user {
  .top {
    font-size: 26px;
    font-weight: bold;
  }
  .content {
    .img_area{
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 10px;
      height: 50px;
      width: 50px;
      border: 1px solid #FAFAFA;
      img{
       width: 100%;
       height: 100%;
      }
    }
  }
}
::v-deep .el-tabs__item {
  width: 120px;
  right: 30px;
}
::v-deep .el-form-item{
  width: 600px;
}
</style>
